package com.ly.datacenter.servlet;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSON;
import net.sf.json.JSONArray;

import com.ly.datacenter.database.definition.HttpParameter4DatabaseCRUD;
import com.ly.datacenter.database.definition.TableDefinition;
import com.ly.datacenter.database.definition.TableDefinitionContainer;
import com.ly.datacenter.http.util.HttpServletUtil;
import com.ly.datacenter.jdbc.parser.JSONParser;
import com.ly.datacenter.jdbc.util.DAOUtil;

/**
 * function:
 * @author watson  email: watson.wu@hotmail.com
 * @date 2009-9-1
 */
public class TableServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String table = req.getParameter(HttpParameter4DatabaseCRUD.X_TABLE);
		if(null==table ||"".equals(table)) return;
		String type = req.getParameter(HttpParameter4DatabaseCRUD.X_TYPE);
		HttpServletUtil.configResponseJSON(req, resp);
		if(null== type || "db".equalsIgnoreCase(type)) {
			TableDefinition definition = TableDefinitionContainer.get(table);
			JSONArray json = new JSONArray();
			if(null == definition) {
				definition = DAOUtil.getTableDefinition(getConnection(), table);
			}
			json.addAll(definition.getCrud());
			resp.getWriter().print(json);
		} else if("json".equalsIgnoreCase(type)) {
			JSON json = JSONParser.getTableDefinition2JSON(table);
			resp.getWriter().print(json);
		} else {
			
		}
	}

	private Connection getConnection() {
		return DataSourceContainer.getConnection();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

}